package com.hulman.oms.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;

/**
 * Base64编解码器
 */
public class Base64
{
    /**
     * 编码
     *
     * @param text
     * @return
     */
    public static String encode(String text)
    {
        try
        {
            return java.util.Base64.getEncoder().encodeToString(text.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解码
     *
     * @param text
     * @return
     */
    public static String decode(String text)
    {
        try
        {
            return new String(java.util.Base64.getDecoder().decode(text), "UTF-8");
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    public static String imageToBase64(String imgFilePath) throws Exception
    {
        // 打开图片文件的输入流
        File file = new File(imgFilePath);
        FileInputStream fileInputStreamReader = new FileInputStream(file);
        byte[] bytes = new byte[(int) file.length()];
        fileInputStreamReader.read(bytes);
        java.util.Base64.Encoder encoder = java.util.Base64.getEncoder();
        String encodedfile = encoder.encodeToString(bytes);
        fileInputStreamReader.close();
        //String base64Prefix = getBase64Prefix(imgFilePath);
        return encodedfile;
    }

    private static String getBase64Prefix(String fileName)
    {
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        switch (extension)
        {
            case "jpg":
            case "jpeg":
                return "data:image/jpeg;base64,";
            case "png":
                return "data:image/png;base64,";
            case "gif":
                return "data:image/gif;base64,";
            case "bmp":
                return "data:image/bmp;base64,";
            case "webp":
                return "data:image/webp;base64,";
            default:
                return "";
        }
    }
}
